import {
	storage
} from '@/common/utils/storage.js'
// import {
// 	getENV,
// 	TEST_ENV,
// 	PRO_ENV
// } from '@/common/urls/baseUrl.js'
// 加密相关
import CryptoJS from 'crypto-js'
import AES from 'crypto-js/aes'
import Base64 from 'crypto-js/enc-base64'
import MD5 from 'crypto-js/md5'
import SHA1 from 'crypto-js/sha1'

export const request = function(params) {
	var encryptOpen = false // 加解密开关
	var AESKey = 'OGFiMGFhM2UwOGI5Y2E0Yw==' // 加解密密钥
	var that = this
	var result = {}
	return new Promise((resolve, reject) => {
		let finalParam = params.data;
		// 增加接口加密功能
		let sortData = JSON.parse(JSON.stringify({}))
		if (params.data && encryptOpen) {
			// 对象按照key值进行排序
			Object.keys(params.data).sort().forEach(function(key) {
				sortData[key] = params.data[key]
			});
			// 第一次base64加密
			let utf8Data = CryptoJS.enc.Utf8.parse(JSON.stringify(sortData))
			let base64Data = Base64.stringify(utf8Data)
			// md5加密
			let MD5Data = MD5(base64Data).toString()
			// sha1加密
			let SHA1Data = SHA1(MD5Data).toString()
			// 截取sign与定义时间戳
			let signData = SHA1Data.substr(6, 20)
			let timestamp = new Date().getTime()
			let addParam = {
				signext: signData,
				timestampext: timestamp
			};
			let newParamData = Object.assign(addParam, sortData)
			// 第二次base64加密
			let utf8DataAgain = CryptoJS.enc.Utf8.parse(JSON.stringify(newParamData))
			let twiceBase64Data = Base64.stringify(utf8DataAgain)
			// AES加密
			let utf8AES = CryptoJS.enc.Base64.parse(that.AESKey)
			let AESKey = utf8AES.toString(CryptoJS.enc.Utf8)
			let encryptedbytes = CryptoJS.AES.encrypt(twiceBase64Data, CryptoJS.enc.Utf8.parse(
				AESKey), {
				mode: CryptoJS.mode.ECB,
			});
			let requestData = encryptedbytes.toString()
			// 最终请求发送的终极加密参数
			finalParam = {
				data: requestData
			}
		}

		// if (TEST_ENV.localeCompare(getENV()) == 0) {
		console.log(`[HTTP][request] ${params.method} / ${params.url}`)
		console.log("[请求参数]", params)

		// }
		uni.request({
			header: params.header,
			url: params.url,
			data: finalParam,
			method: params.method,
			timeout: 5000,
			success: (res) => {
				// if (TEST_ENV.localeCompare(getENV()) == 0) {
				console.log(`[HTTP][response] ${params.method} / ${params.url}`, res)
				// }
				// 请求成功
				if (res.statusCode == 200) {
					if (res.data.data != null) {
						// 解密处理
						if (encryptOpen && typeof res.data.data == 'string') {
							let tmpRes = res
							let uncodeData = res.data.data
							// base64解密
							let base64OBJ = CryptoJS.enc.Base64.parse(uncodeData.toString(
								CryptoJS.enc.Utf8))
							let base64Str = base64OBJ.toString(CryptoJS.enc.Utf8)
							// AES解密
							let encryptedHexStr = CryptoJS.enc.Hex.parse(base64Str)
							let encryptedBase64Str = CryptoJS.enc.Base64.stringify(
								encryptedHexStr)
							// 后端代码默认的是ECB模式
							let utf8AES = CryptoJS.enc.Base64.parse(that.AESKey)
							let AESKey = utf8AES.toString(CryptoJS.enc.Utf8)
							let decryptedbytes = CryptoJS.AES.decrypt(encryptedBase64Str,
								CryptoJS.enc.Utf8.parse(AESKey), {
									mode: CryptoJS.mode.ECB,
								})
							let decryptedStr = CryptoJS.enc.Utf8.stringify(decryptedbytes)
							if (decryptedStr) {
								if (decryptedStr.indexOf('{') > -1 || decryptedStr.indexOf(
										'[') > -1) {
									tmpRes.data.data = JSON.parse(decryptedStr)
								} else {
									// 针对data里面是非对象字符串的情况，不然"12345"会被转成12345，如果超过16位，数字精确度就有误差
									tmpRes.data.data = decryptedStr
								}
							} else {
								tmpRes.data.data = ''
							}
						}
						result.status = true
					} else if (res.data.returnCode == "401" || res.data.returnCode == "10401") {
						// #ifdef APP-PLUS
						if (storage.getStorageDataSync("token")) {
							// token失效
							plus.runtime.quit();
						}
						// #endif
						// #ifndef APP-PLUS
						if (storage.getStorageDataSync("token")) {
							// token失效
							storage.removeStorageDataSync("token")
							uni.showToast({
								title: '登录失效，请重新登录',
								icon: 'none',
								duration: 2000
							})
						}
						result.status = false
						uni.reLaunch({
							url: 'pages/login'
						})
						// #endif
					} else {
						// 请求成功，但数据不存在
						console.log("请求成功，但数据不存在")
						result.status = false
					}
				} else {
					// 请求失败
					console.log("请求失败")
					result.status = false
				}

				result.res = res
				resolve(result)
			},
			fail: function(err) {
				console.error(`[HTTP][error] ${params.method} / ${params.url}`, err)
				result.status = false
				result.res = err
				reject(result)
			}
		})
	})
}
export const header = function(contentType) {
	var header = {}
	header.ContentType = "application/json"
	if (contentType != 'login') {
		header.Authorization = storage.getStorageDataSync("token") || ''
	}
	if (contentType == "formData") {
		header.ContentType = "application/x-www-form-urlencoded;charset=utf-8"
	}
	return header
}